package org.huoran.sakamichi.main.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtilWithProxy{

    // httpClient配置
    final static int REQUEST_TIMEOUT = 1000;
    final static int CONNECTION_TIMEOUT = 1000;
    final static int SOCKET_TIMEOUT = 1000;

    // 代理隧道验证信息
    final static String proxyUser = "HYR5F3865O5Y689D";
    final static String proxyPass = "C4E7375DB76A0F3B";

    // 代理服务器
    final static String proxyHost = "proxy.abuyun.com";
    final static Integer proxyPort = 9020;

    // IP切换协议头
    final static String switchIpHeaderKey = "Proxy-Switch-Ip";
    final static String switchIpHeaderVal = "yes";

    // json返回值key
    public static final String STATUS_CODE_KEY = "status";
    public static final String RESULT_KEY = "result";

    private static PoolingHttpClientConnectionManager cm = null;
    private static HttpRequestRetryHandler httpRequestRetryHandler = null;
    private static HttpHost proxy = null;

    private static CredentialsProvider credsProvider = null;
    private static RequestConfig reqConfig = null;

    static {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();

        Registry registry = RegistryBuilder.create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();

        cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(5);

        proxy = new HttpHost(proxyHost, proxyPort, "http");

        credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPass));

        reqConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(REQUEST_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT)
                .setExpectContinueEnabled(false)
                .setProxy(new HttpHost(proxyHost, proxyPort))
                .build();
    }

    public static JSONObject doRequest(HttpRequestBase httpReq) {
        CloseableHttpResponse httpResp = null;

        try {
            setHeaders(httpReq);

            httpReq.setConfig(reqConfig);

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setConnectionManager(cm)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();

            AuthCache authCache = new BasicAuthCache();
            authCache.put(proxy, new BasicScheme());

            HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authCache);

            httpResp = httpClient.execute(httpReq, localContext);
            int statusCode = httpResp.getStatusLine().getStatusCode();
//            System.out.println(statusCode);
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpResp.getEntity().getContent()));
            StringBuilder sb = new StringBuilder();

            String line;
            while((line = rd.readLine()) != null) {
                sb.append(line);
            }
//            System.out.println(sb.toString());

            JSONObject result = new JSONObject();
            result.put(STATUS_CODE_KEY,statusCode);
            result.put(RESULT_KEY,sb.toString());
            return result;
        } catch (Exception e) {
//            System.out.println(e.fillInStackTrace());
            return null;
        } finally {
            try {
                if (httpResp != null) {
                    httpResp.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置请求头
     *
     * @param httpReq
     */
    private static void setHeaders(HttpRequestBase httpReq) {
        httpReq.setHeader("Accept-Encoding", null);
        httpReq.setHeader(switchIpHeaderKey, switchIpHeaderVal);
    }

    public static JSONObject doGetRequest(String targetUrl) {
        try {
            HttpGet httpGet = new HttpGet(targetUrl);
            JSONObject result = doRequest(httpGet);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static JSONObject doPostRequest(String targetUrl, Map<String,String> paramMap) {
        try {
            // 要访问的目标页面
            HttpPost httpPost = new HttpPost(targetUrl);

            // 设置表单参数
            List params = new ArrayList();
            Set<Entry<String,String>> paramSet = paramMap.entrySet();
            while (paramSet.iterator().hasNext()){
                Entry<String,String> paramEntry = paramSet.iterator().next();
                params.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            // 发送请求
            JSONObject result = doRequest(httpPost);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String targetUrl = "http://h5.damai.cn/drama/votePlayer?playerId=09";
        JSONObject result = doGetRequest(targetUrl);
        System.out.println(result);
    }
}